import { Directive } from "@vue/runtime-core";
import emotions from "@/staticDatas/emotion";

const replaceEmotion = (content: string, className: string): string => {
  // 匹配到的表情
  const matchEmotions = content.match(/\[[\u4e00-\u9fa5(a-z)(0-9)]+\]/g);
  matchEmotions?.forEach((emotion: string): void => {
    const len: number = emotion.length;
    // 提取出[]内的内容
    const word = emotion.slice(1, len - 1);
    if (len >= 3 && len <= 7 && emotions.has(word)) {
      const options = emotions.get(word)!;
      const image: string = `<img draggable="false" class="${className}" data-key="表情" src="https://face.t.sinajs.cn/t4/appstyle/expression/ext/normal/${options.url}" alt="${word}"/>`;
      content = content.replaceAll(emotion, image);
    }
  })
  return content
}

const filterComment: Directive = {
  beforeMount(el, binding): void {
    if (binding.value) {
      /**
       * 评论的内容
       */
      let comment: string = binding.value.content;
      // 过滤 HTML 字符串，防止用户输入恶意内容
      comment = comment.replaceAll(/&/g, "&amp;").replaceAll(/</g, "&lt;").replaceAll(/>/g, "&gt;");
      el.innerHTML = replaceEmotion(comment, binding.value.imgClass);
    }
  },
};

export default filterComment
export { replaceEmotion }